//
//  NetworkTools.swift
//  XKWeibo
//
//  Created by 小k on 15/11/5.
//  Copyright © 2015年 小k. All rights reserved.
//

import UIKit
import AFNetworking


typealias XKRequestCallBack = (result:AnyObject?, error:NSError?)->()

// 定义方法的枚举
enum XKRequestMethod: String {
    case GET = "GET"
    case POST = "POST"
}

// MARK: - 网络工具
class NetworkTools: AFHTTPSessionManager {
    
    // 应用程序信息
    private let appKey = "996734464"
    private let appSecret = "8cad5f14e067c17c2789cbd16a0857c7"
    private let redirectUrl = "http://www.kuwo.cn"
    
    
    // 创建单例
    static let sharedTools:NetworkTools = {
        
       let tools = NetworkTools()
        
        // 设置 反序列化数据的格式  
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
    }()
    
//    /// token 字典
//    var tokenDict: [String: AnyObject]? {
//        return isExpired ? nil : ["access_token": account!.access_token!]
//    }
    
    /// 返回 token 字典
    private var tokenDict: [String: AnyObject]? {
        // 判断 token 是否有效
        if let token = XKUserAccountViewModel.sharedUserAccount.accessToken {
            
            return ["access_token": token]
        }
        
        return nil
    }
    
    
}

// MARK: - 发布微博
extension NetworkTools {
    ///  发布微博
    ///
    ///  - parameter status:   微博文字
    ///  - parameter finished: 完成回调
    func sendStatus(status: String, finished: XKRequestCallBack) {
        
    
        
        /// 1. 设置参数
        var params = [String: AnyObject] ()
        params["status"] = status
        
        /// 2. 处理网络参数
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        /// 3. 发起网络请求
        tokenRequest(.POST, URLString: urlString, parameters: params, finished: finished)
    }
}



// MARK: - 微博数据网络方法
extension NetworkTools {
    func loadStatus (since_id since_id: Int, max_id: Int, flashed:XKRequestCallBack){
        
    /// 1. 创建参数字典
        var params = [String: AnyObject]()
        
        if since_id > 0 {
            params["since_id"] = since_id
        } else if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
     /// 2. 处理网络参数
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
       
    /// 3. 发出请求获取网络数据
        tokenRequest(.GET, URLString: urlString, parameters: params, finished: flashed)
    }
}


// MARK: - OAuth 相关方法
extension NetworkTools {
    ///  加载用户信息
    ///
    ///  - parameter uid:         uid
    ///  - parameter accessToken: accessToken
    ///  - parameter flashed:     完成回调

    func loadUserInfo(uid:String, flashed:XKRequestCallBack) {
        // 1. 处理网络参数
        let urlString = "https://api.weibo.com/2/users/show.json"

        // 2. 创建参数字典
        var params = [String: AnyObject]()
        params["uid"] = uid
        
        // 3.发出请求获取数据
        tokenRequest(.GET, URLString: urlString, parameters: params, finished: flashed)
    }
        
    
    
    
    
    /// OAuth 授权 URL
    var oauthUrl:NSURL {
        
        // 拼接请求路径
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectUrl)"
        return NSURL(string: urlString)!
    }
    
    /// 加载AccessToken
    func loadToken (code:String, flashed:XKRequestCallBack) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameter = [
            "client_id": appKey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl
        ]
        // 发送请求
        requst(.POST, urlString: urlString, parameters: parameter, flashed: flashed)
        
        // 测试代码, 查看转换类型
//        responseSerializer = AFHTTPResponseSerializer()
//        POST(urlString, parameters: parameter, success: { (_, result) -> Void in
//            let string = NSString(data: result as! NSData, encoding: NSUTF8StringEncoding)
//            print(string)
//            }, failure: nil)
    }
    

}

// MARK: - 封装AFN网络请求
extension NetworkTools {
    
    ///  生成并检测字典
    ///
    ///  - parameter parameters: 参数字典
    ///
    ///  - returns: 是否成功
    private func appendToken ( inout parameters:[String: AnyObject]?) -> Bool{
        // 1. 判断token 是否有效
        guard let token = XKUserAccountViewModel.sharedUserAccount.accessToken else {
            return false
        }
        
        // 2. 判断参数字典
        if parameters == nil {
            parameters = [String: AnyObject]()
        }
        
        // 3. 设置token
        parameters!["access_token"] = token
        return true
    }
    
    
    ///  发起带token的网络请求
    ///
    ///  - parameter method:     GET / POST
    ///  - parameter URLString:  URLString
    ///  - parameter parameters: 参数字典
    ///  - parameter finished:   完成回调
    private func tokenRequest(method: XKRequestMethod, URLString: String, var parameters: [String: AnyObject]?, finished: XKRequestCallBack) {
        
        // 1.判断token字典
        if !appendToken(&parameters) {
            // 如果token无效  执行回调通知调用方
            finished(result: nil, error: NSError(domain: "cn.itcast.error", code: -1001, userInfo: ["message": "token 为空"]))
            
            return
        }
        
        // 2. 发起网络请求
        requst(method, urlString: URLString, parameters: parameters, flashed: finished)
    }
    
   
    ///  网络请求
    ///
    ///  - parameter method:     GET / POST
    ///  - parameter urlString:  URLString
    ///  - parameter parameters: 参数字典
    ///  - parameter flashed:    完成回调
    private func requst(method:XKRequestMethod, urlString:String, parameters:[String: AnyObject]?, flashed:XKRequestCallBack) {
        
        let succes = {(task:NSURLSessionDataTask?, result:AnyObject) -> Void in
        // 执行回调
            flashed(result: result, error: nil)
        }
        
        let failure = {(task:NSURLSessionDataTask?, error:NSError) -> Void in
            flashed(result: nil, error: error)
            
        }
        
        // 判断方法 发送请求获取数据
        if method == XKRequestMethod.GET {
            GET(urlString, parameters: parameters, success: succes, failure: failure)
        }else {
            POST(urlString, parameters: parameters, success: succes, failure: failure)
        }

        
    }
    
}
